package com.shuoyue.ycgk.ui.search;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.appcatch.SPUtils;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.base.ListWithPage;
import com.shuoyue.ycgk.entity.Course;
import com.shuoyue.ycgk.entity.HotSearch;
import com.shuoyue.ycgk.entity.News;
import com.shuoyue.ycgk.entity.PaperSet;
import com.shuoyue.ycgk.entity.RecruitmentItem;
import com.shuoyue.ycgk.entity.ShopItem;
import com.shuoyue.ycgk.ui.course.CourseAdapter;
import com.shuoyue.ycgk.ui.course.info.CourseInfoActivity;
import com.shuoyue.ycgk.ui.news.NewsAdapter;
import com.shuoyue.ycgk.ui.news.NewsInfoActivity;
import com.shuoyue.ycgk.ui.papergroups.adapter.PaperSetAdapter;
import com.shuoyue.ycgk.ui.papergroups.groupcommon.PaperCommonInfoActivity;
import com.shuoyue.ycgk.ui.recruitment.newsinfo.NoticeAdapter;
import com.shuoyue.ycgk.ui.recruitment.newsinfo.RecurimentInfoActivity;
import com.shuoyue.ycgk.ui.shop.ShopAdapter;
import com.shuoyue.ycgk.ui.shop.ShopInfoActivity;
import com.shuoyue.ycgk.utils.FlexLayoutMannergerGetter;
import com.shuoyue.ycgk.utils.GridSpacingItemDecoration;
import com.shuoyue.ycgk.utils.SizeUtil;
import com.shuoyue.ycgk.utils.SpacesItemDecoration;
import com.shuoyue.ycgk.utils.XToast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.widget.LinearLayout.VERTICAL;

public class SearchActivity extends BaseMvpActivity<SerchContract.Presenter>
        implements SerchContract.View {
    @BindView(R.id.edit)
    EditText edit;
    @BindView(R.id.search_his)
    RecyclerView searchHis;
    @BindView(R.id.search_hot)
    RecyclerView searchHot;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.refreshlayout)
    SmartRefreshLayout refreshlayout;
    @BindView(R.id.lay_searchTips)
    LinearLayout laySearchTips;


    int modelId;
    String modelName;
    int type;//1 题目 ;2 课程; 3 资讯, 4招考 ,5书籍，6真题;

    ListWithPage listWithPage;
    String searchTitle;

    ShopAdapter bookAdapter;
    NoticeAdapter recurimentAdapter;
    NewsAdapter newsAdapter;
    CourseAdapter courseAdapter;
    PaperSetAdapter paperSetAdapter;

    HotAdapter hotAdapter;
    HisAdapter hisAdapter;
    List<String> his = new ArrayList<>();

    public static void start(Context source, int type, int modelId, String modelName) {
        source.startActivity(new Intent(source, SearchActivity.class)
                .putExtra("type", type)
                .putExtra("modelId", modelId)
                .putExtra("modelName", modelName)
        );
    }


    /**
     * 初始化layouy
     */
    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    /**
     * 初始化布局
     */
    @Override
    protected void initView() {
        type = getIntent().getIntExtra("type", 1);
        modelId = getIntent().getIntExtra("modelId", -1);
        modelName = getIntent().getStringExtra("modelName");
        edit.setOnEditorActionListener((v, actionId, event) -> {
            hintKbTwo();
            listWithPage = null;
            searchTitle = edit.getText().toString();
            search(searchTitle);
            changeHis(searchTitle);
            laySearchTips.setVisibility(View.GONE);
            return true;
        });
        searchHis.setLayoutManager(new FlexboxLayoutManager(mContext));
        searchHis.addItemDecoration(new GridSpacingItemDecoration(3, SizeUtil.dip2px(mContext, 8), false));
        searchHot.setLayoutManager(new FlexboxLayoutManager(mContext));
        searchHot.addItemDecoration(new GridSpacingItemDecoration(3, SizeUtil.dip2px(mContext, 8), false));
        hisAdapter = new HisAdapter(null);
        hotAdapter = new HotAdapter(null);
        searchHis.setAdapter(hisAdapter);
        searchHot.setAdapter(hotAdapter);
        hisAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            String title = (String) adapter.getItem(position);
            edit.setText(title);
            this.searchTitle = title;
            listWithPage = null;
            search(searchTitle);
            laySearchTips.setVisibility(View.GONE);
        });
        hotAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            HotSearch title = (HotSearch) adapter.getItem(position);
            this.searchTitle = title.getSearchName();
            edit.setText(searchTitle);
            listWithPage = null;
            search(searchTitle);
            laySearchTips.setVisibility(View.GONE);
        });
        if (type == 5) {
            recyclerView.setLayoutManager(new GridLayoutManager(mContext, 2));
            recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, SizeUtil.dip2px(mContext, 8), false));
        } else {
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            recyclerView.addItemDecoration(new DividerItemDecoration(mContext, VERTICAL));
        }
        initAdapter();

        refreshlayout.setEnableLoadMore(false);

        refreshlayout.setOnRefreshListener(refreshLayout -> {
            listWithPage = null;
            search(searchTitle);
            refreshLayout.finishRefresh();
        });
        refreshlayout.setOnLoadMoreListener(refreshLayout -> {
            search(searchTitle);
            refreshLayout.finishLoadMore();
        });
        initHis();
    }

    private void getHot() {
        switch (type) {
            case 1:
                mPresenter.searchHot(modelId, 1);
                break;
            case 2:
                mPresenter.searchHot(modelId, 2);
                break;
            case 3:
                mPresenter.searchHot(modelId, 5);
                break;
            case 4:
                mPresenter.searchHot(modelId, 4);
                break;
            case 5:
                mPresenter.searchHot(modelId, 3);
                break;
            case 6:
                mPresenter.searchHot(modelId, 6);
                break;
        }
    }

    void initHis() {
        Gson gson = new Gson();
        String data = "[]";
        switch (type) {
            case 1:
                data = SPUtils.getPrefString(mContext, "search_his_1", "[]");
                break;
            case 2:
                data = SPUtils.getPrefString(mContext, "search_his_2", "[]");
                break;
            case 3:
                data = SPUtils.getPrefString(mContext, "search_his_3", "[]");
                break;
            case 4:
                data = SPUtils.getPrefString(mContext, "search_his_4", "[]");
                break;
            case 5:
                data = SPUtils.getPrefString(mContext, "search_his_5", "[]");
                break;
            case 6:
                data = SPUtils.getPrefString(mContext, "search_his_6", "[]");
                break;
        }
        his = gson.fromJson(data, new TypeToken<List<String>>() {
        }.getType());
        hisAdapter.setNewData(his);

    }

    void changeHis(String newStr) {
        if (his == null) {
            his = new ArrayList<>();
        }
        if (his.contains(newStr)) {
            return;
        }
        List<String> saveData = new ArrayList<>();
        saveData.add(newStr);

        if (his.size() < 6) {
            saveData.addAll(his);
        } else {
            saveData.addAll(his.subList(0, 5));
        }
        Gson gson = new Gson();
        String dataStr = gson.toJson(saveData);

        switch (type) {
            case 1:
                SPUtils.setPrefString(mContext, "search_his_1", dataStr);
                break;
            case 2:
                SPUtils.setPrefString(mContext, "search_his_2", dataStr);
                break;
            case 3:
                SPUtils.setPrefString(mContext, "search_his_3", dataStr);
                break;
            case 4:
                SPUtils.setPrefString(mContext, "search_his_4", dataStr);
                break;
            case 5:
                SPUtils.setPrefString(mContext, "search_his_5", dataStr);
                break;
            case 6:
                SPUtils.setPrefString(mContext, "search_his_6", dataStr);
                break;
        }
        hisAdapter.setNewData(saveData);
        his = saveData;
    }

    void clearHis() {
        his.clear();
        hisAdapter.notifyDataSetChanged();

        switch (type) {
            case 1:
                SPUtils.setPrefString(mContext, "search_his_1", "[]");
                break;
            case 2:
                SPUtils.setPrefString(mContext, "search_his_2", "[]");
                break;
            case 3:
                SPUtils.setPrefString(mContext, "search_his_3", "[]");
                break;
            case 4:
                SPUtils.setPrefString(mContext, "search_his_4", "[]");
                break;
            case 5:
                SPUtils.setPrefString(mContext, "search_his_5", "[]");
                break;
            case 6:
                SPUtils.setPrefString(mContext, "search_his_6", "[]");
                break;
        }
    }

    void initAdapter() {
        switch (type) {
            case 2:
                courseAdapter = new CourseAdapter(null);
                recyclerView.setAdapter(courseAdapter);
                courseAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                    Course course = (Course) adapter.getItem(position);
                    switch (view.getId()) {
                        case R.id.lay_all:
                            startActivity(new Intent(mContext, CourseInfoActivity.class)
                                    .putExtra("id", course.getId()));

                            break;
                    }
                });
                registEmptyView(courseAdapter);
                break;
            case 3:
                newsAdapter = new NewsAdapter(null);
                recyclerView.setAdapter(newsAdapter);
                newsAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                    News news = (News) adapter.getItem(position);
                    startActivity(new Intent(mContext, NewsInfoActivity.class)
                            .putExtra("id", news.getId()));
                });
                registEmptyView(newsAdapter);
                break;
            case 4:
                recurimentAdapter = new NoticeAdapter(null);
                recyclerView.setAdapter(recurimentAdapter);
                recurimentAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                    RecruitmentItem recruitmentItem = (RecruitmentItem) adapter.getItem(position);
                    startActivity(new Intent(mContext, RecurimentInfoActivity.class)
                            .putExtra("id", recruitmentItem.getId())
                    );
                });
                registEmptyView(recurimentAdapter);

                break;
            case 5:
                bookAdapter = new ShopAdapter(null);
                recyclerView.setAdapter(bookAdapter);
                bookAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                    ShopItem shopItem = (ShopItem) adapter.getItem(position);
                    startActivity(new Intent(mContext, ShopInfoActivity.class)
                            .putExtra("id", shopItem.getId()));
                });
                registEmptyView(bookAdapter);
                break;
            case 6:
                paperSetAdapter = new PaperSetAdapter(null);
                recyclerView.setAdapter(paperSetAdapter);
                paperSetAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                    PaperSet paperSet = (PaperSet) adapter.getItem(position);
                    PaperCommonInfoActivity.start(mContext, paperSet.getId(), 1,-1);
                });
                registEmptyView(paperSetAdapter);
                break;
        }
    }

    private void search(String keyWord) {
        if (TextUtils.isEmpty(keyWord)) {
            XToast.toast(mContext, "请输入关键字");
            return;
        }
        switch (type) {
            case 2:
                mPresenter.searchCourse(keyWord, modelId, listWithPage == null ? 1 : listWithPage.getCurrent() + 1);
                break;
            case 3:
                mPresenter.searchNews(keyWord, modelId, listWithPage == null ? 1 : listWithPage.getCurrent() + 1);
                break;
            case 4:
                mPresenter.searchRecuriment(keyWord, listWithPage == null ? 1 : listWithPage.getCurrent() + 1);
                break;
            case 5:
                mPresenter.searchBooks(keyWord, modelId, listWithPage == null ? 1 : listWithPage.getCurrent() + 1);
                break;
            case 6:
                mPresenter.searchRealPaper(keyWord, listWithPage == null ? 1 : listWithPage.getCurrent() + 1);
                break;
        }
    }

    @Override
    public void initData() {
        super.initData();
        mPresenter = new SerchContract.Presenter();
        mPresenter.attachView(this);
        getHot();
    }

    @OnClick({R.id.back, R.id.delete, R.id.x})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.delete:
                clearHis();
                break;
            case R.id.x:
                edit.setText("");
                laySearchTips.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
                if (bookAdapter != null) {
                    bookAdapter.clear();
                }
                if (courseAdapter != null) {
                    courseAdapter.clear();
                }
                if (recurimentAdapter != null) {
                    recurimentAdapter.clear();
                }
                if (newsAdapter != null) {
                    newsAdapter.clear();
                }

                break;
        }
    }

    @Override
    public void searchHotSuc(List<HotSearch> list) {
        hotAdapter.setNewData(list);
        refreshlayout.finishRefresh();
        refreshlayout.finishLoadMore();
    }

    @Override
    public void searchRecuSuc(ListWithPage<RecruitmentItem> list) {
        recyclerView.setVisibility(View.VISIBLE);
        listWithPage = list;
        if (list.getCurrent() == 1) {
            recurimentAdapter.resetData(list.getRecords());
        } else {
            recurimentAdapter.addData(list.getRecords());
        }
        refreshlayout.setEnableLoadMore(list.getCurrent() != list.getPages() && list.getPages() > 0);

        refreshlayout.finishRefresh();
        refreshlayout.finishLoadMore();
    }

    @Override
    public void searchNewsSuc(ListWithPage<News> list) {
        recyclerView.setVisibility(View.VISIBLE);

        listWithPage = list;
        if (list.getCurrent() == 1) {
            newsAdapter.resetData(list.getRecords());
        } else {
            newsAdapter.addData(list.getRecords());
        }
        refreshlayout.setEnableLoadMore(list.getCurrent() != list.getPages() && list.getPages() > 0);

        refreshlayout.finishRefresh();
        refreshlayout.finishLoadMore();
    }

    @Override
    public void searchCourseSuc(ListWithPage<Course> list) {
        recyclerView.setVisibility(View.VISIBLE);

        listWithPage = list;
        if (list.getCurrent() == 1) {
            courseAdapter.resetData(list.getRecords());
        } else {
            courseAdapter.addData(list.getRecords());
        }
        refreshlayout.setEnableLoadMore(list.getCurrent() != list.getPages() && list.getPages() > 0);
        refreshlayout.finishRefresh();
        refreshlayout.finishLoadMore();
    }

    @Override
    public void searchBookSuc(ListWithPage<ShopItem> list) {
        recyclerView.setVisibility(View.VISIBLE);

        listWithPage = list;
        if (list.getCurrent() == 1) {
            bookAdapter.resetData(list.getRecords());
        } else {
            bookAdapter.addData(list.getRecords());
        }
        refreshlayout.setEnableLoadMore(list.getCurrent() != list.getPages() && list.getPages() > 0);
        refreshlayout.finishRefresh();
        refreshlayout.finishLoadMore();
    }

    @Override
    public void searchRealSuc(ListWithPage<PaperSet> list) {
        recyclerView.setVisibility(View.VISIBLE);

        listWithPage = list;
        if (list.getCurrent() == 1) {
            paperSetAdapter.resetData(list.getRecords());
        } else {
            paperSetAdapter.addData(list.getRecords());
        }
        refreshlayout.setEnableLoadMore(list.getCurrent() != list.getPages() && list.getPages() > 0);
        refreshlayout.finishRefresh();
        refreshlayout.finishLoadMore();
    }

}
